#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import cv2
import numpy as np
import pytesseract
import sys
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

import logging


def setup_custom_logger(name):
    formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
                                  datefmt='%Y-%m-%d %H:%M:%S')
    # handler = logging.FileHandler('log.txt', mode='w')
    # handler.setFormatter(formatter)
    screen_handler = logging.StreamHandler(stream=sys.stdout)
    screen_handler.setFormatter(formatter)
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    # logger.addHandler(handler)
    logger.addHandler(screen_handler)
    return logger


logger = setup_custom_logger('app')

pytesseract.pytesseract.tesseract_cmd = "/usr/bin/tesseract"

card_champion = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/card_champion.png'),
                             cv2.COLOR_BGR2GRAY)
daily_task = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/daily_task.png'),
                          cv2.COLOR_BGR2GRAY)
main_page = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/main_page.png'),
                         cv2.COLOR_BGR2GRAY)


def getFilteredImg(img):
    FILTER_MIN = np.array([0, 0, 0], np.uint8)
    FILTER_MAX = np.array([70, 70, 70], np.uint8)
    frame_threshed = cv2.inRange(img, FILTER_MIN, FILTER_MAX)
    # frame_threshed2 = cv2.cvtColor(frame_threshed, cv2.COLOR_HSV2BGR)
    result = cv2.bitwise_or(img, img, mask=frame_threshed)
    return result


def getContentStop(img):
    # FILTER_MIN = np.array([0, 0, 0], np.uint8)
    # FILTER_MAX = np.array([70, 70, 70], np.uint8)
    # frame_threshed = cv2.inRange(img, FILTER_MIN, FILTER_MAX)
    # res = cv2.bitwise_or(img, img, mask=frame_threshed)
    res = img[641:666, 1187:1238]
    return pytesseract.image_to_string(res, lang='chi_sim')


def getContentMatch(img):
    res = img[639:675, 593:680]
    # plt.imshow(res), plt.show()
    return pytesseract.image_to_string(res, lang='chi_sim')


def getContentSpendTime(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    frame_threshed = cv2.inRange(img, 80, 255)
    grey = cv2.bitwise_or(img, img, mask=frame_threshed)
    # res = res[645:667, 608:632]
    # plt.imshow(grey), plt.show()
    spendTimeImg = grey[350:375, 795:878]  # 已用时间
    spendTimeImgText = pytesseract.image_to_string(spendTimeImg, lang='chi_sim')
    spendTimeContentImg = grey[353:372, 884:936]  # 已用时间 具体值
    spendTimeContentImgText = pytesseract.image_to_string(spendTimeContentImg)
    return (spendTimeImgText, spendTimeContentImgText)


def getContentConfirm(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = img[613:646, 592:686]
    frame_threshed = cv2.inRange(img, 160, 255)
    img = cv2.bitwise_or(img, img, mask=frame_threshed)
    # plt.imshow(img), plt.show()
    return pytesseract.image_to_string(img, lang='chi_sim')


def getContentConcel(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = img[645:667, 608:670]
    ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
    # frame_threshed = cv2.inRange(img, 100, 255)
    # img = cv2.bitwise_or(img, img, mask=frame_threshed)
    # cv2.imwrite('/home/liusen/mount/192.168.1.99_ShareFiles/TEST/00011_split_2.png', img)

    plt.imshow(img), plt.show()
    return pytesseract.image_to_string(img, lang='chi_sim')  # 取消 显示不出来


def getContentRound(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = img[645:667, 608:632]
    frame_threshed = cv2.inRange(img, 87, 255)
    img = cv2.bitwise_or(img, img, mask=frame_threshed)
    # plt.imshow(img), plt.show()
    return pytesseract.image_to_string(img, lang='chi_sim')


def getContentCard(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = img[350:386, 86:156]
    frame_threshed = cv2.inRange(img, 87, 255)
    img = cv2.bitwise_or(img, img, mask=frame_threshed)
    # plt.imshow(img), plt.show()
    return pytesseract.image_to_string(img, lang='chi_sim')


def getContentMainPage(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = img[382:403, 417:467]
    frame_threshed = cv2.inRange(img, 0, 255)
    img = cv2.bitwise_or(img, img, mask=frame_threshed)
    # plt.imshow(img), plt.show()
    template = main_page
    # plt.imshow(img), plt.show()
    # plt.imshow(template), plt.show()
    # cv2.imwrite('/home/liusen/IdeaWorkspace/wechat-jump/mijing/main_page.png', img)
    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    logger.debug("main_page match value : {}".format(res[0][0]))
    loc = np.where(res >= 0.8)
    if len(list(zip(*loc[::-1]))) == 1:
        return True
    else:
        return False


def getContentDailyTask(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = img[124:156, 575:705]
    frame_threshed = cv2.inRange(img, 87, 255)
    img = cv2.bitwise_or(img, img, mask=frame_threshed)
    # plt.imshow(img), plt.show()
    template = daily_task
    # plt.imshow(img), plt.show()
    # plt.imshow(template), plt.show()
    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    logger.debug("daily_task match value : {}".format(res[0][0]))
    loc = np.where(res >= 0.8)
    if len(list(zip(*loc[::-1]))) == 1:
        return True
    else:
        return False


def getContentCardChampion(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = img[350:386, 86:156]
    frame_threshed = cv2.inRange(img, 87, 255)
    img = cv2.bitwise_or(img, img, mask=frame_threshed)
    template = card_champion
    # plt.imshow(img), plt.show()
    # plt.imshow(template), plt.show()

    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    logger.debug("card_champion match value : {}".format(res[0][0]))
    loc = np.where(res >= 0.8)
    # plt.imshow(img), plt.show()
    # cv2.imwrite('/home/liusen/IdeaWorkspace/wechat-jump/mijing/card_champion.png', img)
    if len(list(zip(*loc[::-1]))) == 1:
        return True
    else:
        return False


def getContentCardInPrepareStage(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = img[274:296, 85:169]
    frame_threshed = cv2.inRange(img, 87, 255)
    img = cv2.bitwise_or(img, img, mask=frame_threshed)
    plt.imshow(img), plt.show()
    logger.debug(pytesseract.image_to_string(img, lang='chi_sim'))


def getContentCardInMatchStage(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = img[341:377, 397:467]
    frame_threshed = cv2.inRange(img, 120, 255)
    img = cv2.bitwise_or(img, img, mask=frame_threshed)
    plt.imshow(img), plt.show()
    return pytesseract.image_to_string(img, lang='chi_sim')


def test1():
    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00001.png'
    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00013.png'
    path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing3/09.png'

    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00010.png'
    img = cv2.imread(path)
    # img = getFilteredImg(img)
    # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # ret, img = cv2.threshold(img, 150, 255, cv2.THRESH_BINARY)
    # cropImg = thresh1[641:666, 1187:1238] # 右下结束按钮
    # cropImg2 = img[641:666, 1187:1238] # 右下结束按钮
    # img_edges = cv2.Canny(cropImg, 100, 200)
    # plt.subplot(121), plt.imshow(cropImg)
    # plt.subplot(122), plt.imshow(cropImg2)
    # plt.subplot(122), plt.imshow(img_edges)
    # plt.show()
    # plt.imshow(img), plt.show()
    # logger.debug(pytesseract.image_to_string(cropImg, lang='chi_sim'))
    # logger.debug(pytesseract.image_to_string(cropImg2, lang='chi_sim'))

    img = img[654:678, 168:186]  # 回合数
    img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

    # (h, w) = img.shape[:2]
    # center = (w // 2, h // 2)
    # M = cv2.getRotationMatrix2D(center, -5, 1.0)
    # img = cv2.warpAffine(img, M, (w, h))

    # ret, img = cv2.threshold(img, 251, 255, cv2.THRESH_BINARY)
    # (h, w) = img.shape[:2]
    # width = 600
    # n = width / float(w)
    # newsize = (width, int(h * n))
    # print(newsize)
    # img = cv2.resize(img, newsize, interpolation=cv2.INTER_CUBIC)
    plt.imshow(img), plt.show()
    logger.debug(pytesseract.image_to_string(img, lang='eng', config='--psm 10'))

    # config='--psm 10 --eom 3 -c tessedit_char_whitelist=0123456789'


def test6():
    # print(list(map(lambda x: '0' + str(x), range(1, 10))))
    for s in list(map(lambda x: '0' + str(x), range(1, 10))):
        srcPath = '/home/liusen/IdeaWorkspace/wechat-jump/mijing3/' + s + '.png'
        descPath = '/home/liusen/IdeaWorkspace/wechat-jump/mijing3/' + s + '_crop.png'
        img = cv2.imread(srcPath)
        img = img[654:678, 168:186]  # 回合数
        cv2.imwrite(descPath, img)


def test():
    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00001.png'
    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00010.png'
    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00011.png'
    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00012.png'
    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00013.png'
    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00018.png'
    path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00019.png'
    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00020.png'
    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00026.png'
    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00027.png'

    img = cv2.imread(path)

    # cardStr = getContentCardBeginningStage(img)
    # cardStr = getContentCard(img)
    cardStr = getContentCardChampion(img)
    # cardStr = getContentDailyTask(img)
    # cardStr = getContentMainPage(img)
    # cardStr = getContentConcel(img)
    # cardStr = getContentCardInPrepareStage(img)

    logger.debug('cardStr={}'.format(cardStr))
    if cardStr == '擂主':
        logger.debug('遇到擂主了，认真玩吧')
    if cardStr == '':
        logger.debug('null')
        # logger.debug(getContentCard(img))


def test2():
    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/Figure_1.png'
    path = '/home/liusen/mount/192.168.1.99_ShareFiles/TEST/00011_split_2.png'

    img = cv2.imread(path)
    # img = cv2.Canny(img, 100, 200)
    plt.imshow(img), plt.show()

    cardStr = pytesseract.image_to_string(img, lang='chi_sim')
    logger.debug('cardStr={}'.format(cardStr))


def test3():
    # player = cv2.imread('/home/liusen/mount/192.168.1.99_ShareFiles/TEST/00011_split_1.png')
    player = cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/00011_split.png')
    # img = cv2.imread('/home/liusen/mount/192.168.1.99_ShareFiles/TEST/00011_split_1.png')
    # img = cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/Figure_1.png')
    img = cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/00011_split.png')
    h = player.shape[0]
    w = player.shape[1]
    res = cv2.matchTemplate(img, player, cv2.TM_CCOEFF_NORMED)
    loc = np.where(res >= 0.8)
    # logger.debug(loc[::-1])
    # logger.debug(*loc[::-1])
    # logger.debug(zip(*loc[::-1]))
    # logger.debug(list(zip(*loc[::-1])))
    # logger.debug(len(list(zip(*loc[::-1]))))
    if len(list(zip(*loc[::-1]))) == 1:
        logger.debug("aaa")
    for pt in zip(*loc[::-1]):
        cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)

    # min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    # # top_left = min_loc
    # top_left = max_loc
    # bottom_right = (top_left[0] + w, top_left[1] + h)
    # cv2.rectangle(img, top_left, bottom_right, 255, 2)
    plt.subplot(221), plt.imshow(img, cmap="gray")
    plt.title('Original Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(222), plt.imshow(player, cmap="gray")
    plt.title('template Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(223), plt.imshow(res, cmap="gray")
    plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
    plt.subplot(224), plt.imshow(img, cmap="gray")
    plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
    plt.show()


def test4():
    path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00000.png'
    img = cv2.imread(path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = img[611:652, 537:742]

    # img[:, :, 2] = 0
    # img[:, :, 1] = 0
    # flat_list = [s2 for s1 in img for s2 in s1]

    # # 创建一个三维的绘图工程
    # ax = plt.subplot(111, projection='3d')
    # ax.scatter([e[0] for e in flat_list], [e[1] for e in flat_list], [e[2] for e in flat_list], c='r')  # 绘制数据点
    # ax.set_zlabel('B')
    # ax.set_ylabel('G')
    # ax.set_xlabel('R')


    # unique, counts = np.unique(np.array(flat_list), axis=0, return_counts=True)
    # print(unique, counts)

    # print(list(zip([e[0] for e in unique], [e[1] for e in unique], [e[2] for e in unique], counts)))

    # print(list(zip(unique, counts)))
    # img2 = np.zeros((256, 256, 4), np.uint8)
    #
    # for i in range(len(unique)):
    #     print(unique[i],counts[i])


    # cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
    # rgba
    # print(img2)
    # a = dict(zip(unique, counts))
    # print(a)

    # plt.imshow(img)

    # color = ('b', 'g', 'r')
    # for i, col in enumerate(color):
    #     histr = cv2.calcHist([img], [i], None, [256], [0, 256])
    #     plt.plot(histr, color=col)
    #     plt.xlim([0, 256])
    # plt.imshow(img)

    hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
    # print(hsv)
    hist = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
    hist = cv2.cvtColor(hist, cv2.COLOR_GRAY2RGB)
    plt.imshow(hist, interpolation='nearest')

    # plt.subplot(122), plt.imshow(img_edges)
    plt.show()


def test7():
    img = cv2.imread('/home/liusen/WebStormWorkSpace/auto_script/Screenshot_2018-07-18-14-35-16-120_com.jd.jrapp.png')
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.plot(111), plt.imshow(img)
    plt.show()


if __name__ == '__main__':
    test7()
    sys.exit(0)
